<script setup lang="ts">
import { ref } from 'vue'
import { useAuthStore } from '@/store/modules/auth'

const emit = defineEmits<{
  (e: 'success'): void
  (e: 'switch-to-register'): void
}>()

const authStore = useAuthStore()
const form = ref({
  username: '',
  password: '',
})
const error = ref('')
const loading = ref(false)

const handleSubmit = async () => {
  if (!form.value.username || !form.value.password) {
    error.value = '请填写所有字段'
    return
  }

  try {
    loading.value = true
    await authStore.login(form.value.username, form.value.password)
    emit('success')
    window.location.reload()
  } catch (err: any) {
    error.value = err.response?.data?.message || '登录失败，请重试'
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <form @submit.prevent="handleSubmit" class="auth-form">
    <div class="form-group">
      <label for="username">用户名</label>
      <input
        id="username"
        v-model="form.username"
        type="text"
        required
        placeholder="请输入用户名"
      />
    </div>

    <div class="form-group">
      <label for="password">密码</label>
      <input
        id="password"
        v-model="form.password"
        type="password"
        required
        placeholder="请输入密码"
      />
    </div>

    <div v-if="error" class="error-message">{{ error }}</div>

    <button type="submit" :disabled="loading" class="submit-button">
      {{ loading ? '登录中...' : '登录' }}
    </button>

    <div class="register-link">
      还没有账号？
      <a href="#" @click.prevent="emit('switch-to-register')">立即注册</a>
    </div>
  </form>
</template>

<style scoped lang="scss">
.auth-form {
  .form-group {
    margin-bottom: 1rem;

    label {
      display: block;
      margin-bottom: 0.5rem;
      color: #4b5563;
      font-weight: 500;
    }

    input {
      width: 100%;
      padding: 0.75rem;
      border: 1px solid #d1d5db;
      border-radius: 6px;
      font-size: 1rem;

      &:focus {
        outline: none;
        border-color: #6366f1;
        box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
      }
    }
  }
}

.error-message {
  color: #dc2626;
  margin-bottom: 1rem;
  padding: 0.5rem;
  background-color: #fef2f2;
  border-radius: 4px;
  font-size: 0.9rem;
}

.submit-button {
  width: 100%;
  padding: 0.75rem;
  background-color: #6366f1;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;

  &:hover {
    background-color: #4f46e5;
  }

  &:disabled {
    background-color: #9ca3af;
    cursor: not-allowed;
  }
}

.register-link {
  text-align: center;
  margin-top: 1.5rem;
  color: #6b7280;

  a {
    color: #6366f1;
    text-decoration: none;
    font-weight: 500;

    &:hover {
      text-decoration: underline;
    }
  }
}
</style>
